package util;
//通过此工具类可以直接创建SQL语句,创建集合,执行update或quary方法,

import java.sql.*;
import java.util.List;
import java.util.ResourceBundle;

public class DBUtils {
    public Connection connection = null;
    public PreparedStatement pps = null;
    public ResultSet rs = null;
    protected int k = 0;//受影响的行数
    private  static String url;//此处需注意更换数据库
    private static String driver;
    private static String username;
    private static String password ;

    //加载驱动
    static {
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("db");
            driver = bundle.getString("driver");
            url = bundle.getString("url");
            username = bundle.getString("user");
            password = bundle.getString("password");
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获得连接
    public Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //创建通道
    public PreparedStatement getPreparedStatement(String sql) {

        try {
            getConnection();
            pps = connection.prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    //给占位符赋值
    public void setParams(List list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                try {
                    pps.setObject(i + 1, list.get(i));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    //增删改
    public int update(String sql, List params) {
        try {
            getPreparedStatement(sql);
            setParams(params);
            k = pps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return k;
    }

    //查询方法
    public ResultSet query(String sql, List list) {
        try {
            getPreparedStatement(sql);
            setParams(list);
            rs = pps.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭资源
    public void closeall() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pps != null) {
                pps.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

